package com.fileupload.fileupload.handler;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.fileupload.fileupload.domain.entity.ExportExcelDate;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ResultContext;
import org.apache.ibatis.session.ResultHandler;

import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Slf4j
public class DownExcelDateResultHandler implements ResultHandler<ExportExcelDate> {
    private ExcelWriter excelWriter = null;
    private WriteSheet writeSheet001 = null;
    @Getter
    private String execlPath;
    private String fileName;

    /**
     * 处理结果
     * @param resultContext
     */
    @Override
    public void handleResult(ResultContext<? extends ExportExcelDate> resultContext) {
        //判断是否为第一行
        if (resultContext.getResultCount() == 1){
            // 临时文件的路径
            URL resource = this.getClass().getResource("/");
            String path = resource.getPath().replaceFirst("/","");
            // 临时文件的名字
            this.fileName = UUID.randomUUID().toString().replace("-", "") +".xlsx";
            this.execlPath = path + fileName;
            // 1 创建excel 文件
            excelWriter = EasyExcel.write(execlPath, ExportExcelDate.class).build();
            // 2 创建sheet
            writeSheet001 = EasyExcel.writerSheet("sheet001").build();
        }
        // 每次返回的数据
        ExportExcelDate resultObject = resultContext.getResultObject();
        log.info("resultObject:{}", resultObject);
        List<ExportExcelDate> bigDates = Arrays.asList(resultObject);
        excelWriter.write(bigDates, writeSheet001);
    }

    /**
     * 只要保证在全部的handleResult执行完再执行
     */
    public void end(){
        // 关闭excwel
        excelWriter.finish();
    }
}
